﻿define(function (require) {
    var service = require('ezdesk/utility/service');
    require('ezdesk/utility/datetime');

    window.WorkitemStatus = {
        Ongoing: 0,  // 正在进行中
        Completed: 1,  // 已经完成
        Expired: 2,  // 过期了
        WaitingForConfirm: 3,  // 等待确认
        Ready: 4  // 没有负责人，等待分配
    };

    window.Workitem = Backbone.Model.extend({
        initialize: function () {
            if (this.get("StatusValue") == WorkitemStatus.Ongoing) {
                this.set({ "CommandText": "完成" });
                this.set({ "CommandClass": "green" });
            }
            else if (this.get("StatusValue") == WorkitemStatus.WaitingForConfirm) {
                this.set({ "CommandText": "确认" });
                this.set({ "CommandClass": "blue" });
            }
            else if (this.get("StatusValue") == WorkitemStatus.Expired) {
                this.set({ "CommandText": "完成" });
                this.set({ "CommandClass": "rosy" });
            }

            //project and  task
            if (this.get('Project')) {
                var projectInfo = this.get('Project');
                this.set({ "ProjectInfo": projectInfo.Name });

                if (this.get('Task'))
                    this.set({ "ProjectInfo": this.get('Task').Name + " - " + projectInfo.Name });
            } else {
                this.set({ "ProjectInfo": "" });
            }

            //planon 
            var diff = this.get('PlanOn') ?
                (Date.fromEpoch(this.get('PlanOn')).getTime() - new Date().getTime()) / 3600 / 1000 / 24 : null;
            var planOnStr = "";
            if (diff > 0)
                planOnStr = "剩余" + Math.ceil(diff) + "天";
            else if (diff == 0)
                planOnStr = "今天到期";
            else if (diff < 0)
                planOnStr = "过期" + Math.floor(-diff) + "天";

            this.set({ "PlanOnStr": planOnStr });

        },
        command: function (e) {
            var _self = this;
            if (_self.get("StatusValue") == WorkitemStatus.Ongoing || _self.get("StatusValue") == WorkitemStatus.Expired) {
                service.DoFinishWorkitem(function (statusInfo) {
                    _self.trigger('finished', [_self.cid, statusInfo]);
                },
                {
                    workitemId: _self.get("Id"),
                    points: _self.get("Points")
                });

            }
            else if (_self.get("StatusValue") == WorkitemStatus.WaitingForConfirm) {
                service.DoConfirmWorkitem(function (statusInfo) {
                    _self.trigger('confirmed', [_self.cid, statusInfo]);
                },
                {
                    workitemId: _self.get("Id")
                });
            }

        }
    });

});
